package com.banciyuan.bcywebview.base.service;

import android.app.IntentService;
import android.content.Intent;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.RequestFuture;
import com.banciyuan.bcywebview.api.StartApi;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.universalimageloader.core.download.BaseImageDownloader;
import com.banciyuan.bcywebview.utils.universalimageloader.core.download.ImageDownloader;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.File;
import java.io.InputStream;

import de.greenrobot.daoexample.model.StartUpInfo;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;

/**
 * Created by squall on 2015/10/21.
 */
public class InitBackGroundService extends IntentService {

    private RequestQueue queue;

    public InitBackGroundService() {
        super("InitBackGroundService");
    }

    public InitBackGroundService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        queue = VolleyQueue.getRquest(this);
        String url = HttpUtils.BASE_URL + StartApi.getStart();
        RequestFuture<String> future = RequestFuture.newFuture();
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, future, future);
        queue.add(requestParam);
        try {
            String result = future.get();
            if (StatusCodeUtils.dealStatusCode(result, InitBackGroundService.this)) {
                JSONObject jsonObject = new JSONObject(result);
                StartUpInfo startUpInfo = new Gson().fromJson(jsonObject.getString("data"), StartUpInfo.class);
                if (startUpInfo.getVersion() == -1) {
                    SPHelper.putString(InitBackGroundService.this, SPConstant.SPNAME_INITBACKURL, SPConstant.URL, "");
                    SPHelper.putInt(InitBackGroundService.this, SPConstant.SPNAME_INITBACKGROUND, SPConstant.VERSION, 0);
                    SPHelper.putString(InitBackGroundService.this, SPConstant.SPNAME_INITBACKURL, SPConstant.STARTUP_PAGE_INFOR, new Gson().toJson(startUpInfo));
                } else {
                    dealImg(startUpInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dealImg(final StartUpInfo newStartUpInfo) throws Exception {
        int oldversion = SPHelper.getInt(this, SPConstant.SPNAME_INITBACKGROUND, SPConstant.VERSION, 0);
        final int newVersion = newStartUpInfo.getVersion();
        String imgurl = newStartUpInfo.getStart_cover();
        File file = new File(ImageManager.getImageFile(getApplicationContext()) + newVersion);
        if (oldversion < newVersion || !file.exists()) {
            ImageDownloader imageDownloader = new BaseImageDownloader(this);
            InputStream is = imageDownloader.getStream(imgurl, null, false);
            BufferedSource source = Okio.buffer(Okio.source(is));
            File dic = new File(ImageManager.getImageFile(getApplicationContext()));
            if (!dic.exists()) {
                dic.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            BufferedSink sink = Okio.buffer(Okio.sink(file));
            sink.writeAll(source);
            sink.close();
            source.close();
            SPHelper.putString(InitBackGroundService.this, SPConstant.SPNAME_INITBACKURL, SPConstant.URL, file.getAbsolutePath());
            SPHelper.putInt(InitBackGroundService.this, SPConstant.SPNAME_INITBACKGROUND, SPConstant.VERSION, newVersion);
            SPHelper.putString(InitBackGroundService.this, SPConstant.SPNAME_INITBACKURL, SPConstant.STARTUP_PAGE_INFOR, new Gson().toJson(newStartUpInfo));

        }
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }
}
